package com.smartlink.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.smartlink.pojo.Classroom;

public class ClassroomDaoImple implements Dao<Integer, Classroom> {
	private SessionFactory sessionFactory;
	private Session session;

	public Session getSession() {
		this.session = sessionFactory.getCurrentSession();
		return session;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public boolean insert(Classroom clsroom) {
		getSession().save(clsroom);
		return true;
	}

	@Override
	public boolean delete(Classroom v) {
		getSession().delete(v);
		// TODO Auto-generated method stub
		return true;
	}

	public boolean delete(Integer id) {
		String hql = "DELETE Classroom WHERE id=?";
		int n = getSession().createQuery(hql).setInteger(0, id).executeUpdate();
		if (n > 0) {
			return true;
		} else {
			return false;
		}
		// TODO Auto-generated method stub

	}

	@Override
	public boolean deleteById(Integer k) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean update(Classroom v) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Classroom findById(Integer k) {
		// TODO Auto-generated method stub LEFT JOIN FETCH
		// c.sensorses,c.settings

		Classroom clsroom = (Classroom) getSession().get(Classroom.class, k);
		return clsroom;
	}

	public Classroom findByDeviceId(String deviceId) {
		String hql = "FROM Classroom WHERE deviceId=?";
		Query query = getSession().createQuery(hql).setString(0, deviceId);
		Classroom classroom = (Classroom) query.list().get(0);
		return classroom;
	}

	@Override
	public List<Classroom> getAll() {
		String hql = "FROM Classroom c LEFT JOIN FETCH c.building ";
		Query query = getSession().createQuery(hql);
		@SuppressWarnings("unchecked")
		List<Classroom> clList = query.list();
		return clList;
	}

	/**
	 * 使用原生SQL获取关于教室的信息
	 * 
	 * @return
	 */
	public List<String> getClassroomInfoList() {
		String sql = "SELECT c.`id`,c.`bluetooth`,c.`name_number` FROM classroom c;";
		SQLQuery query = getSession().createSQLQuery(sql);
		List<String> list = query.list();
		return list;
	}

	@Override
	public List<Classroom> getAll(Integer currentIndex, Integer pageSize) {
		// TODO Auto-generated method stub
		// FROM Classroom c LEFT JOIN FETCH c.building
		String hql = "FROM Classroom";
		Query query = getSession().createQuery(hql);
		query.setFirstResult((currentIndex - 1) * pageSize).setMaxResults(pageSize);
		@SuppressWarnings("unchecked")
		List<Classroom> clList = query.list();
		return clList;
	}

}
